import 'package:casdon/common/state/common_net_status.dart';

import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/login/application/notifier/login_notifier.dart';

import 'package:casdon/modules/login/data/api/valide_code_type.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/update_pwd_state.dart';

import 'package:casdon/modules/login/domain/usecases/send_emailCode_usecase.dart';
import 'package:casdon/modules/login/domain/usecases/update_pwd_usecase.dart';
import 'package:casdon/modules/login/domain/usecases/verify_otp_usecase.dart';
import 'package:casdon/modules/login/providers/login_code_provider.dart';
import 'package:casdon/modules/login/domain/usecases/send_sms_usecase.dart';

import 'package:flutter_riverpod/flutter_riverpod.dart';

class LoginUpdatePwdNotifier extends LoginNotifier<UpdatePwdState> {
  UpdatePwdtep step = UpdatePwdtep.sendCode;
  Future<void> sendCode({
    SendCodeSource source = SendCodeSource.accountPage,
  }) async {
    if (CommonNetStatus.loading == state.status) {
      return;
    }
    step = UpdatePwdtep.sendCode;

    if (state.account == null) {
      setFailure(msg: "请输入账号");
      return;
    }
    // 清除不需要的状态信息
    state = state.copyWith(
      source: source,
      status: CommonNetStatus.loading,
      message: null,
      code: null,
      errorCode: null,
      newPwd: null,
    );
    if (state.account!.isPhoneNum()) {
      _sendSmsCode(state.account!);
    } else if (state.account!.isEmail()) {
      _sendEmailCode(state.account!);
    } else {
      setFailure(msg: "账号格式不正确");
    }
  }

  void updateNewPwd(String value) {
    state = state.copyWith(
      newPwd: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void updateAccount(String value) {
    state = state.copyWith(
      account: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void updateCode(String value) {
    state = state.copyWith(
      code: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  Future<void> verifyCode() async {
    if (state.status == CommonNetStatus.loading) {
      return;
    }
    if (state.account == null || state.code == null) {
      setFailure(msg: "账号或密码为空");
      return;
    }
    step = UpdatePwdtep.verifyCode;
    state = state.copyWith(
      status: CommonNetStatus.loading,
      message: null,
      errorCode: null,
      newPwd: null,
    );

    try {
      VerifyOtpUsecase verifyUsecase = ref.read(verifyOtpUsecaseProvider);
      final ret = await verifyUsecase.execute(
        state.account!,
        state.code!,
        ValideCodeType.modifyPwd,
      );

      if (ret == true) {
        setSuccess("验证码正确");
      } else {
        setFailure(msg: "验证码错误");
      }
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "验证码校验失败");
      Log.e("验证码校验失败", e.toString(), StackTrace.current);
    }
  }

  void _sendSmsCode(String phone) async {
    try {
      SendSmsUsecase sendSmsUsecase = ref.read(sendSmsUsecaseProvider);
      final ret = await sendSmsUsecase.execute(phone, ValideCodeType.modifyPwd);
      if (ret.success == true) {
        setSuccess("发送验证码成功");
      } else {
        setFailure(msg: ret.message ?? "发送验证码失败");
      }
    } catch (e) {
      setFailure(msg: getErrorMessage(e));
    }
  }

  void _sendEmailCode(String email) async {
    try {
      SendEmailcodeUsecase sendEmailcodeUsecase = ref.read(
        sendEmailcodeProvider,
      );
      final ret = await sendEmailcodeUsecase.execute(
        email,
        ValideCodeType.modifyPwd,
      );
      if (ret == true) {
        setSuccess("发送验证码成功");
      } else {
        setFailure(msg: "发送验证码失败");
      }
    } catch (e) {
      setFailure(msg: getErrorMessage(e));
    }
  }

  // 验证码登录
  void updatePwd() async {
    if (state.status == CommonNetStatus.loading) {
      return;
    }
    if (state.account == null || state.newPwd == null) {
      setFailure(msg: "账号或密码为空");
      return;
    }
    step = UpdatePwdtep.updatePwd;

    state = state.copyWith(
      status: CommonNetStatus.loading,
      message: null,
      errorCode: null,
    );
    try {
      final updatePwdUsecase = ref.read(updatePwdUsecaseProvider);

      final ret = await updatePwdUsecase.execute(
        userName: state.account!,
        newPassword: state.newPwd!,
      );

      // final authStorage = ref.read(authStorageProvider.notifier);
      // await authStorage.saveToken(ret.access_token);
      setSuccess("修改密码成功");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "修改密码失败，请稍后再试！");
    }
  }

  @override
  UpdatePwdState build() {
    ref.onDispose(() {
      Log.d("已经销毁：LoginUpdatePwdNotifier");
    });
    return UpdatePwdState.initial();
  }
}

final loginModifyPwdNotifierProvider =
    NotifierProvider.autoDispose<LoginUpdatePwdNotifier, UpdatePwdState>(
      () => LoginUpdatePwdNotifier(),
    );
